﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;


namespace iPlaylistSync
{
    class Program
    {
        static string libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic) + @"\iTunes\iTunes Music Library.xml";
        static string playlist = "";
        static string objFolder = "";

        // args:[playlist name,objPath,library.xml path]
        static void Main(string[] args)
        {
            ParamConfigure(args);
            
            PlaylistReader reader = new PlaylistReader(libraryPath);
            Track[] list = null;
            try
            {
                list = reader.GetTracks(playlist);
                list.Sync(objFolder);
                list.Save(objFolder + playlist + ".m3u8", Track.Playlist.M3U8);
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine("Cannot find playlist named \""+playlist+"\".");
            }
        }

        public static void ParamConfigure(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.WriteLine("Enter the name of playlist: ");
                playlist = Console.ReadLine();

                Console.WriteLine("Enter the object directory: ");
                objFolder = Console.ReadLine();

                Console.WriteLine("Enter the path of iTunesMusicLibrary.xml, empty for default path: ");
                string tmpPath = Console.ReadLine();
                if(!String.IsNullOrEmpty(tmpPath))
                {
                    libraryPath = tmpPath;
                }
            }
            else if (args != null &&  (args.Length > 3 || args.Length < 2))
            {
                Console.WriteLine("Bad Arguments. All arguments:\n iPLExtractor.exe %playList% %objectFolder% [%library path%] ");
                //Environment.Exit(1);
                ParamConfigure(null);
            }
            else if (args.Length == 3)
            {
                playlist = args[0];
                objFolder = args[1];
                libraryPath = args[2];
            }
            else if (args.Length == 2)
            {
                playlist = args[0];
                objFolder = args[1];
            }

            objFolder = objFolder.Replace("/", "\\");
            if (!objFolder.EndsWith("\\"))
            {
                objFolder += "\\";
            }
        }

    }
}